package com.example.search.controller;

import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.search.dto.UserSearchDto;
import com.example.model.search.pojo.SearchArticleVo;
import com.example.search.service.ArticleSearchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/")
@Tag(name = "搜索文章管理")
@Slf4j
public class ArticleSearchController {
    @Autowired
    private ArticleSearchService articleSearchService;

    @PostMapping("/article/search/{page}/{pageSize}")
    @Operation(summary = "搜索文章")
    public R search(@RequestBody UserSearchDto userSearchDto, @PathVariable(value = "page") Long page, @PathVariable(value = "pageSize") Long pageSize) throws IOException {
        // 1、 检查参数是否有效
        if (userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }

        Page< SearchArticleVo > searchArticleVoPage = articleSearchService.search(userSearchDto, page, pageSize);
        List< SearchArticleVo > searchArticleList = searchArticleVoPage.getContent();

        // 2、 计算总记录数和总页数
        long total = searchArticleVoPage.getTotalElements();
        long pages = searchArticleVoPage.getTotalPages();

        // 3、 返回搜索结果
        Map< String, Object > map = new HashMap<>();
        map.put("total", total);
        map.put("pageSize", pageSize);
        map.put("pages", pages);
        map.put("page", page);
        map.put("articleList", searchArticleList);
        if (!searchArticleList.isEmpty()) {
            return R.ok("搜索文章分页数据成功").data(map);
        } else if (searchArticleVoPage.isEmpty()) {
            log.info(map.toString());
            return R.error("搜索文章分页没找到数据");
        } else {
            log.info(map.toString());
            return R.error("搜索文章分页数据失败");
        }
    }
}
